home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / CRC.ZIP / crc.txt next >
Text File  |  1995-03-14  |  91KB  |  2,071 lines

  1. =============================================================================
  2. A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS
  3. ==================================================
  4. "Everything you wanted to know about CRC algorithms, but were afraid
  5. to ask for fear that errors in your understanding might be detected."
  6.  
  7. Version : 3.
  8. Date    : 19 August 1993.
  9. Author  : Ross N. Williams.
  10. Net     : ross@guest.adelaide.edu.au.
  11. FTP     : ftp.adelaide.edu.au/pub/rocksoft/crc_v3.txt
  12. Company : Rocksoft^tm Pty Ltd.
  13. Snail   : 16 Lerwick Avenue, Hazelwood Park 5066, Australia.
  14. Fax     : +61 8 373-4911 (c/- Internode Systems Pty Ltd).
  15. Phone   : +61 8 379-9217 (10am to 10pm Adelaide Australia time).
  16. Note    : "Rocksoft" is a trademark of Rocksoft Pty Ltd, Australia.
  17. Status  : Copyright (C) Ross Williams, 1993. However, permission is
  18.           granted to make and distribute verbatim copies of this
  19.           document provided that this information block and copyright
  20.           notice is included. Also, the C code modules included
  21.           in this document are fully public domain.
  22. Thanks  : Thanks to Jean-loup Gailly (jloup@chorus.fr) and Mark Adler
  23.           (me@quest.jpl.nasa.gov) who both proof read this document
  24.           and picked out lots of nits as well as some big fat bugs.
  25.  
  26. Table of Contents
  27. -----------------
  28.     Abstract
  29.  1. Introduction: Error Detection
  30.  2. The Need For Complexity
  31.  3. The Basic Idea Behind CRC Algorithms
  32.  4. Polynomical Arithmetic
  33.  5. Binary Arithmetic with No Carries
  34.  6. A Fully Worked Example
  35.  7. Choosing A Poly
  36.  8. A Straightforward CRC Implementation
  37.  9. A Table-Driven Implementation
  38. 10. A Slightly Mangled Table-Driven Implementation
  39. 11. "Reflected" Table-Driven Implementations
  40. 12. "Reversed" Polys
  41. 13. Initial and Final Values
  42. 14. Defining Algorithms Absolutely
  43. 15. A Parameterized Model For CRC Algorithms
  44. 16. A Catalog of Parameter Sets for Standards
  45. 17. An Implementation of the Model Algorithm
  46. 18. Roll Your Own Table-Driven Implementation
  47. 19. Generating A Lookup Table
  48. 20. Summary
  49. 21. Corrections
  50.  A. Glossary
  51.  B. References
  52.  C. References I Have Detected But Haven't Yet Sighted
  53.  
  54.  
  55. Abstract
  56. --------
  57. This document explains CRCs (Cyclic Redundancy Codes) and their
  58. table-driven implementations in full, precise detail. Much of the
  59. literature on CRCs, and in particular on their table-driven
  60. implementations, is a little obscure (or at least seems so to me).
  61. This document is an attempt to provide a clear and simple no-nonsense
  62. explanation of CRCs and to absolutely nail down every detail of the
  63. operation of their high-speed implementations. In addition to this,
  64. this document presents a parameterized model CRC algorithm called the
  65. "Rocksoft^tm Model CRC Algorithm". The model algorithm can be
  66. parameterized to behave like most of the CRC implementations around,
  67. and so acts as a good reference for describing particular algorithms.
  68. A low-speed implementation of the model CRC algorithm is provided in
  69. the C programming language. Lastly there is a section giving two forms
  70. of high-speed table driven implementations, and providing a program
  71. that generates CRC lookup tables.
  72.  
  73.  
  74. 1. Introduction: Error Detection
  75. --------------------------------
  76. The aim of an error detection technique is to enable the receiver of a
  77. message transmitted through a noisy (error-introducing) channel to
  78. determine whether the message has been corrupted. To do this, the
  79. transmitter constructs a value (called a checksum) that is a function
  80. of the message, and appends it to the message. The receiver can then
  81. use the same function to calculate the checksum of the received
  82. message and compare it with the appended checksum to see if the
  83. message was correctly received. For example, if we chose a checksum
  84. function which was simply the sum of the bytes in the message mod 256
  85. (i.e. modulo 256), then it might go something as follows. All numbers
  86. are in decimal.
  87.  
  88.    Message                    :  6 23  4
  89.    Message with checksum      :  6 23  4 33
  90.    Message after transmission :  6 27  4 33
  91.  
  92. In the above, the second byte of the message was corrupted from 23 to
  93. 27 by the communications channel. However, the receiver can detect
  94. this by comparing the transmitted checksum (33) with the computer
  95. checksum of 37 (6 + 27 + 4). If the checksum itself is corrupted, a
  96. correctly transmitted message might be incorrectly identified as a
  97. corrupted one. However, this is a safe-side failure. A dangerous-side
  98. failure occurs where the message and/or checksum is corrupted in a
  99. manner that results in a transmission that is internally consistent.
  100. Unfortunately, this possibility is completely unavoidable and the best
  101. that can be done is to minimize its probability by increasing the
  102. amount of information in the checksum (e.g. widening the checksum from
  103. one byte to two bytes).
  104.  
  105. Other error detection techniques exist that involve performing complex
  106. transformations on the message to inject it with redundant
  107. information. However, this document addresses only CRC algorithms,
  108. which fall into the class of error detection algorithms that leave the
  109. data intact and append a checksum on the end. i.e.:
  110.  
  111.       <original intact message> <checksum>
  112.  
  113.  
  114. 2. The Need For Complexity
  115. --------------------------
  116. In the checksum example in the previous section, we saw how a
  117. corrupted message was detected using a checksum algorithm that simply
  118. sums the bytes in the message mod 256:
  119.  
  120.    Message                    :  6 23  4
  121.    Message with checksum      :  6 23  4 33
  122.    Message after transmission :  6 27  4 33
  123.  
  124. A problem with this algorithm is that it is too simple. If a number of
  125. random corruptions occur, there is a 1 in 256 chance that they will
  126. not be detected. For example:
  127.  
  128.    Message                    :  6 23  4
  129.    Message with checksum      :  6 23  4 33
  130.    Message after transmission :  8 20  5 33
  131.  
  132. To strengthen the checksum, we could change from an 8-bit register to
  133. a 16-bit register (i.e. sum the bytes mod 65536 instead of mod 256) so
  134. as to apparently reduce the probability of failure from 1/256 to
  135. 1/65536. While basically a good idea, it fails in this case because
  136. the formula used is not sufficiently "random"; with a simple summing
  137. formula, each incoming byte affects roughly only one byte of the
  138. summing register no matter how wide it is. For example, in the second
  139. example above, the summing register could be a Megabyte wide, and the
  140. error would still go undetected. This problem can only be solved by
  141. replacing the simple summing formula with a more sophisticated formula
  142. that causes each incoming byte to have an effect on the entire
  143. checksum register.
  144.  
  145. Thus, we see that at least two aspects are required to form a strong
  146. checksum function:
  147.  
  148.    WIDTH: A register width wide enough to provide a low a-priori
  149.           probability of failure (e.g. 32-bits gives a 1/2^32 chance
  150.           of failure).
  151.  
  152.    CHAOS: A formula that gives each input byte the potential to change
  153.           any number of bits in the register.
  154.  
  155. Note: The term "checksum" was presumably used to describe early
  156. summing formulas, but has now taken on a more general meaning
  157. encompassing more sophisticated algorithms such as the CRC ones. The
  158. CRC algorithms to be described satisfy the second condition very well,
  159. and can be configured to operate with a variety of checksum widths.
  160.  
  161.  
  162. 3. The Basic Idea Behind CRC Algorithms
  163. ---------------------------------------
  164. Where might we go in our search for a more complex function than
  165. summing? All sorts of schemes spring to mind. We could construct
  166. tables using the digits of pi, or hash each incoming byte with all the
  167. bytes in the register. We could even keep a large telephone book
  168. on-line, and use each incoming byte combined with the register bytes
  169. to index a new phone number which would be the next register value.
  170. The possibilities are limitless.
  171.  
  172. However, we do not need to go so far; the next arithmetic step
  173. suffices. While addition is clearly not strong enough to form an
  174. effective checksum, it turns out that division is, so long as the
  175. divisor is about as wide as the checksum register.
  176.  
  177. The basic idea of CRC algorithms is simply to treat the message as an
  178. enormous binary number, to divide it by another fixed binary number,
  179. and to make the remainder from this division the checksum. Upon
  180. receipt of the message, the receiver can perform the same division and
  181. compare the remainder with the "checksum" (transmitted remainder).
  182.  
  183. Example: Suppose the the message consisted of the two bytes (6,23) as
  184. in the previous example. These can be considered to be the hexadecimal
  185. number 0617 which can be considered to be the binary number
  186. 0000-0110-0001-0111. Suppose that we use a checksum register one-byte
  187. wide and use a constant divisor of 1001, then the checksum is the
  188. remainder after 0000-0110-0001-0111 is divided by 1001. While in this
  189. case, this calculation could obviously be performed using common
  190. garden variety 32-bit registers, in the general case this is messy. So
  191. instead, we'll do the division using good-'ol long division which you
  192. learnt in school (remember?). Except this time, it's in binary:
  193.  
  194.           ...0000010101101 = 00AD =  173 = QUOTIENT
  195.          ____-___-___-___-
  196. 9= 1001 ) 0000011000010111 = 0617 = 1559 = DIVIDEND
  197. DIVISOR   0000.,,....,.,,,
  198.           ----.,,....,.,,,
  199.            0000,,....,.,,,
  200.            0000,,....,.,,,
  201.            ----,,....,.,,,
  202.             0001,....,.,,,
  203.             0000,....,.,,,
  204.             ----,....,.,,,
  205.              0011....,.,,,
  206.              0000....,.,,,
  207.              ----....,.,,,
  208.               0110...,.,,,
  209.               0000...,.,,,
  210.               ----...,.,,,
  211.                1100..,.,,,
  212.                1001..,.,,,
  213.                ====..,.,,,
  214.                 0110.,.,,,
  215.                 0000.,.,,,
  216.                 ----.,.,,,
  217.                  1100,.,,,
  218.                  1001,.,,,
  219.                  ====,.,,,
  220.                   0111.,,,
  221.                   0000.,,,
  222.                   ----.,,,
  223.                    1110,,,
  224.                    1001,,,
  225.                    ====,,,
  226.                     1011,,
  227.                     1001,,
  228.                     ====,,
  229.                      0101,
  230.                      0000,
  231.                      ----
  232.                       1011
  233.                       1001
  234.                       ====
  235.                       0010 = 02 = 2 = REMAINDER
  236.  
  237.  
  238. In decimal this is "1559 divided by 9 is 173 with a remainder of 2".
  239.  
  240. Although the effect of each bit of the input message on the quotient
  241. is not all that significant, the 4-bit remainder gets kicked about
  242. quite a lot during the calculation, and if more bytes were added to
  243. the message (dividend) it's value could change radically again very
  244. quickly. This is why division works where addition doesn't.
  245.  
  246. In case you're wondering, using this 4-bit checksum the transmitted
  247. message would look like this (in hexadecimal): 06172 (where the 0617
  248. is the message and the 2 is the checksum). The receiver would divide
  249. 0617 by 9 and see whether the remainder was 2.
  250.  
  251. 4. Polynomical Arithmetic
  252. -------------------------
  253. While the division scheme described in the previous section is very
  254. very similar to the checksumming schemes called CRC schemes, the CRC
  255. schemes are in fact a bit weirder, and we need to delve into some
  256. strange number systems to understand them.
  257.  
  258. The word you will hear all the time when dealing with CRC algorithms
  259. is the word "polynomial". A given CRC algorithm will be said to be
  260. using a particular polynomial, and CRC algorithms in general are said
  261. to be operating using polynomial arithmetic. What does this mean?
  262.  
  263. Instead of the divisor, dividend (message), quotient, and remainder
  264. (as described in the previous section) being viewed as positive
  265. integers, they are viewed as polynomials with binary coefficients.
  266. This is done by treating each number as a bit-string whose bits are
  267. the coefficients of a polynomial. For example, the ordinary number 23
  268. (decimal) is 17 (hex) and 10111 binary and so it corresponds to the
  269. polynomial:
  270.  
  271.    1*x^4 + 0*x^3 + 1*x^2 + 1*x^1 + 1*x^0
  272.  
  273. or, more simply:
  274.  
  275.    x^4 + x^2 + x^1 + x^0
  276.  
  277. Using this technique, the message, and the divisor can be represented
  278. as polynomials and we can do all our arithmetic just as before, except
  279. that now it's all cluttered up with Xs. For example, suppose we wanted
  280. to multiply 1101 by 1011. We can do this simply by multiplying the
  281. polynomials:
  282.  
  283. (x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
  284. = (x^6 + x^4 + x^3
  285.  + x^5 + x^3 + x^2
  286.  + x^3 + x^1 + x^0) = x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0
  287.  
  288. At this point, to get the right answer, we have to pretend that x is 2
  289. and propagate binary carries from the 3*x^3 yielding
  290.  
  291.    x^7 + x^3 + x^2 + x^1 + x^0
  292.  
  293. It's just like ordinary arithmetic except that the base is abstracted
  294. and brought into all the calculations explicitly instead of being
  295. there implicitly. So what's the point?
  296.  
  297. The point is that IF we pretend that we DON'T know what x is, we CAN'T
  298. perform the carries. We don't know that 3*x^3 is the same as x^4 + x^3
  299. because we don't know that x is 2. In this true polynomial arithmetic
  300. the relationship between all the coefficients is unknown and so the
  301. coefficients of each power effectively become strongly typed;
  302. coefficients of x^2 are effectively of a different type to
  303. coefficients of x^3.
  304.  
  305. With the coefficients of each power nicely isolated, mathematicians
  306. came up with all sorts of different kinds of polynomial arithmetics
  307. simply by changing the rules about how coefficients work. Of these
  308. schemes, one in particular is relevant here, and that is a polynomial
  309. arithmetic where the coefficients are calculated MOD 2 and there is no
  310. carry; all coefficients must be either 0 or 1 and no carries are
  311. calculated. This is called "polynomial arithmetic mod 2". Thus,
  312. returning to the earlier example:
  313.  
  314. (x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
  315. = (x^6 + x^4 + x^3
  316.  + x^5 + x^3 + x^2
  317.  + x^3 + x^1 + x^0)
  318. = x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0
  319.  
  320. Under the other arithmetic, the 3*x^3 term was propagated using the
  321. carry mechanism using the knowledge that x=2. Under "polynomial
  322. arithmetic mod 2", we don't know what x is, there are no carries, and
  323. all coefficients have to be calculated mod 2. Thus, the result
  324. becomes:
  325.  
  326. = x^6 + x^5 + x^4 + x^3 + x^2 + x^1 + x^0
  327.  
  328. As Knuth [Knuth81] says (p.400):
  329.  
  330.    "The reader should note the similarity between polynomial
  331.    arithmetic and multiple-precision arithmetic (Section 4.3.1), where
  332.    the radix b is substituted for x. The chief difference is that the
  333.    coefficient u_k of x^k in polynomial arithmetic bears little or no
  334.    relation to its neighboring coefficients x^{k-1} [and x^{k+1}], so
  335.    the idea of "carrying" from one place to another is absent. In fact
  336.    polynomial arithmetic modulo b is essentially identical to multiple
  337.    precision arithmetic with radix b, except that all carries are
  338.    suppressed."
  339.  
  340. Thus polynomical arithmetic mod 2 is just binary arithmetic mod 2 with
  341. no carries. While polynomials provide useful mathematical machinery in
  342. more analytical approaches to CRC and error-correction algorithms, for
  343. the purposes of exposition they provide no extra insight and some
  344. encumbrance and have been discarded in the remainder of this document
  345. in favour of direct manipulation of the arithmetical system with which
  346. they are isomorphic: binary arithmetic with no carry.
  347.  
  348.  
  349. 5. Binary Arithmetic with No Carries
  350. ------------------------------------
  351. Having dispensed with polynomials, we can focus on the real arithmetic
  352. issue, which is that all the arithmetic performed during CRC
  353. calculations is performed in binary with no carries. Often this is
  354. called polynomial arithmetic, but as I have declared the rest of this
  355. document a polynomial free zone, we'll have to call it CRC arithmetic
  356. instead. As this arithmetic is a key part of CRC calculations, we'd
  357. better get used to it. Here we go:
  358.  
  359. Adding two numbers in CRC arithmetic is the same as adding numbers in
  360. ordinary binary arithmetic except there is no carry. This means that
  361. each pair of corresponding bits determine the corresponding output bit
  362. without reference to any other bit positions. For example:
  363.  
  364.         10011011
  365.        +11001010
  366.         --------
  367.         01010001
  368.         --------
  369.  
  370. There are only four cases for each bit position:
  371.  
  372.    0+0=0
  373.    0+1=1
  374.    1+0=1
  375.    1+1=0  (no carry)
  376.  
  377. Subtraction is identical:
  378.  
  379.         10011011
  380.        -11001010
  381.         --------
  382.         01010001
  383.         --------
  384.  
  385. with
  386.  
  387.    0-0=0
  388.    0-1=1  (wraparound)
  389.    1-0=1
  390.    1-1=0
  391.  
  392. In fact, both addition and subtraction in CRC arithmetic is equivalent
  393. to the XOR operation, and the XOR operation is its own inverse. This
  394. effectively reduces the operations of the first level of power
  395. (addition, subtraction) to a single operation that is its own inverse.
  396. This is a very convenient property of the arithmetic.
  397.  
  398. By collapsing of addition and subtraction, the arithmetic discards any
  399. notion of magnitude beyond the power of its highest one bit. While it
  400. seems clear that 1010 is greater than 10, it is no longer the case
  401. that 1010 can be considered to be greater than 1001. To see this, note
  402. that you can get from 1010 to 1001 by both adding and subtracting the
  403. same quantity:
  404.  
  405.    1010 = 1010 + 0011
  406.    1010 = 1010 - 0011
  407.  
  408. This makes nonsense of any notion of order.
  409.  
  410. Having defined addition, we can move to multiplication and division.
  411. Multiplication is absolutely straightforward, being the sum of the
  412. first number, shifted in accordance with the second number.
  413.  
  414.         1101
  415.       x 1011
  416.         ----
  417.         1101
  418.        1101.
  419.       0000..
  420.      1101...
  421.      -------
  422.      1111111  Note: The sum uses CRC addition
  423.      -------
  424.  
  425. Division is a little messier as we need to know when "a number goes
  426. into another number". To do this, we invoke the weak definition of
  427. magnitude defined earlier: that X is greater than or equal to Y iff
  428. the position of the highest 1 bit of X is the same or greater than the
  429. position of the highest 1 bit of Y. Here's a fully worked division
  430. (nicked from [Tanenbaum81]).
  431.  
  432.             1100001010
  433.        _______________
  434. 10011 ) 11010110110000
  435.         10011,,.,,....
  436.         -----,,.,,....
  437.          10011,.,,....
  438.          10011,.,,....
  439.          -----,.,,....
  440.           00001.,,....
  441.           00000.,,....
  442.           -----.,,....
  443.            00010,,....
  444.            00000,,....
  445.            -----,,....
  446.             00101,....
  447.             00000,....
  448.             -----,....
  449.              01011....
  450.              00000....
  451.              -----....
  452.               10110...
  453.               10011...
  454.               -----...
  455.                01010..
  456.                00000..
  457.                -----..
  458.                 10100.
  459.                 10011.
  460.                 -----.
  461.                  01110
  462.                  00000
  463.                  -----
  464.                   1110 = Remainder
  465.  
  466. That's really it. Before proceeding further, however, it's worth our
  467. while playing with this arithmetic a bit to get used to it.
  468.  
  469. We've already played with addition and subtraction, noticing that they
  470. are the same thing. Here, though, we should note that in this
  471. arithmetic A+0=A and A-0=A. This obvious property is very useful
  472. later.
  473.  
  474. In dealing with CRC multiplication and division, it's worth getting a
  475. feel for the concepts of MULTIPLE and DIVISIBLE.
  476.  
  477. If a number A is a multiple of B then what this means in CRC
  478. arithmetic is that it is possible to construct A from zero by XORing
  479. in various shifts of B. For example, if A was 0111010110 and B was 11,
  480. we could construct A from B as follows:
  481.  
  482.                   0111010110
  483.                 = .......11.
  484.                 + ....11....
  485.                 + ...11.....
  486.                   .11.......
  487.  
  488. However, if A is 0111010111, it is not possible to construct it out of
  489. various shifts of B (can you see why? - see later) so it is said to be
  490. not divisible by B in CRC arithmetic.
  491.  
  492. Thus we see that CRC arithmetic is primarily about XORing particular
  493. values at various shifting offsets.
  494.  
  495. 6. A Fully Worked Example
  496. -------------------------
  497. Having defined CRC arithmetic, we can now frame a CRC calculation as
  498. simply a division, because that's all it is! This section fills in the
  499. details and gives an example.
  500.  
  501. To perform a CRC calculation, we need to choose a divisor. In maths
  502. marketing speak the divisor is called the "generator polynomial" or
  503. simply the "polynomial", and is a key parameter of any CRC algorithm.
  504. It would probably be more friendly to call the divisor something else,
  505. but the poly talk is so deeply ingrained in the field that it would
  506. now be confusing to avoid it. As a compromise, we will refer to the
  507. CRC polynomial as the "poly". Just think of this number as a sort of
  508. parrot. "Hello poly!"
  509.  
  510. You can choose any poly and come up with a CRC algorithm. However,
  511. some polys are better than others, and so it is wise to stick with the
  512. tried an tested ones. A later section addresses this issue.
  513.  
  514. The width (position of the highest 1 bit) of the poly is very
  515. important as it dominates the whole calculation. Typically, widths of
  516. 16 or 32 are chosen so as to simplify implementation on modern
  517. computers. The width of a poly is the actual bit position of the
  518. highest bit. For example, the width of 10011 is 4, not 5. For the
  519. purposes of example, we will chose a poly of 10011 (of width W of 4).
  520.  
  521. Having chosen a poly, we can proceed with the calculation. This is
  522. simply a division (in CRC arithmetic) of the message by the poly. The
  523. only trick is that W zero bits are appended to the message before the
  524. CRC is calculated. Thus we have:
  525.  
  526.    Original message                : 1101011011
  527.    Poly                            :      10011
  528.    Message after appending W zeros : 11010110110000
  529.  
  530. Now we simply divide the augmented message by the poly using CRC
  531. arithmetic. This is the same division as before:
  532.  
  533.             1100001010 = Quotient (nobody cares about the quotient)
  534.        _______________
  535. 10011 ) 11010110110000 = Augmented message (1101011011 + 0000)
  536. =Poly  10011,,.,,....
  537.         -----,,.,,....
  538.          10011,.,,....
  539.          10011,.,,....
  540.          -----,.,,....
  541.           00001.,,....
  542.           00000.,,....
  543.           -----.,,....
  544.            00010,,....
  545.            00000,,....
  546.            -----,,....
  547.             00101,....
  548.             00000,....
  549.             -----,....
  550.              01011....
  551.              00000....
  552.              -----....
  553.               10110...
  554.               10011...
  555.               -----...
  556.                01010..
  557.                00000..
  558.                -----..
  559.                 10100.
  560.                 10011.
  561.                 -----.
  562.                  01110
  563.                  00000
  564.                  -----
  565.                   1110 = Remainder = THE CHECKSUM!!!!
  566.  
  567. The division yields a quotient, which we throw away, and a remainder,
  568. which is the calculated checksum. This ends the calculation.
  569.  
  570. Usually, the checksum is then appended to the message and the result
  571. transmitted. In this case the transmission would be: 11010110111110.
  572.  
  573. At the other end, the receiver can do one of two things:
  574.  
  575.    a. Separate the message and checksum. Calculate the checksum for
  576.       the message (after appending W zeros) and compare the two
  577.       checksums.
  578.  
  579.    b. Checksum the whole lot (without appending zeros) and see if it
  580.       comes out as zero!
  581.  
  582. These two options are equivalent. However, in the next section, we
  583. will be assuming option b because it is marginally mathematically
  584. cleaner.
  585.  
  586. A summary of the operation of the class of CRC algorithms:
  587.  
  588.    1. Choose a width W, and a poly G (of width W).
  589.    2. Append W zero bits to the message. Call this M'.
  590.    3. Divide M' by G using CRC arithmetic. The remainder is the checksum.
  591.  
  592. That's all there is to it.
  593.  
  594. 7. Choosing A Poly
  595. ------------------
  596. Choosing a poly is somewhat of a black art and the reader is referred
  597. to [Tanenbaum81] (p.130-132) which has a very clear discussion of this
  598. issue. This section merely aims to put the fear of death into anyone
  599. who so much as toys with the idea of making up their own poly. If you
  600. don't care about why one poly might be better than another and just
  601. want to find out about high-speed implementations, choose one of the
  602. arithmetically sound polys listed at the end of this section and skip
  603. to the next section.
  604.  
  605. First note that the transmitted message T is a multiple of the poly.
  606. To see this, note that 1) the last W bits of T is the remainder after
  607. dividing the augmented (by zeros remember) message by the poly, and 2)
  608. addition is the same as subtraction so adding the remainder pushes the
  609. value up to the next multiple. Now note that if the transmitted
  610. message is corrupted in transmission that we will receive T+E where E
  611. is an error vector (and + is CRC addition (i.e. XOR)). Upon receipt of
  612. this message, the receiver divides T+E by G. As T mod G is 0, (T+E)
  613. mod G = E mod G. Thus, the capacity of the poly we choose to catch
  614. particular kinds of errors will be determined by the set of multiples
  615. of G, for any corruption E that is a multiple of G will be undetected.
  616. Our task then is to find classes of G whose multiples look as little
  617. like the kind of line noise (that will be creating the corruptions) as
  618. possible. So let's examine the kinds of line noise we can expect.
  619.  
  620. SINGLE BIT ERRORS: A single bit error means E=1000...0000. We can
  621. ensure that this class of error is always detected by making sure that
  622. G has at least two bits set to 1. Any multiple of G will be
  623. constructed using shifting and adding and it is impossible to
  624. construct a value with a single bit by shifting an adding a single
  625. value with more than one bit set, as the two end bits will always
  626. persist.
  627.  
  628. TWO-BIT ERRORS: To detect all errors of the form 100...000100...000
  629. (i.e. E contains two 1 bits) choose a G that does not have multiples
  630. that are 11, 101, 1001, 10001, 100001, etc. It is not clear to me how
  631. one goes about doing this (I don't have the pure maths background),
  632. but Tanenbaum assures us that such G do exist, and cites G with 1 bits
  633. (15,14,1) turned on as an example of one G that won't divide anything
  634. less than 1...1 where ... is 32767 zeros.
  635.  
  636. ERRORS WITH AN ODD NUMBER OF BITS: We can catch all corruptions where
  637. E has an odd number of bits by choosing a G that has an even number of
  638. bits. To see this, note that 1) CRC multiplication is simply XORing a
  639. constant value into a register at various offsets, 2) XORing is simply
  640. a bit-flip operation, and 3) if you XOR a value with an even number of
  641. bits into a register, the oddness of the number of 1 bits in the
  642. register remains invariant. Example: Starting with E=111, attempt to
  643. flip all three bits to zero by the repeated application of XORing in
  644. 11 at one of the two offsets (i.e. "E=E XOR 011" and "E=E XOR 110")
  645. This is nearly isomorphic to the "glass tumblers" party puzzle where
  646. you challenge someone to flip three tumblers by the repeated
  647. application of the operation of flipping any two. Most of the popular
  648. CRC polys contain an even number of 1 bits. (Note: Tanenbaum states
  649. more specifically that all errors with an odd number of bits can be
  650. caught by making G a multiple of 11).
  651.  
  652. BURST ERRORS: A burst error looks like E=000...000111...11110000...00.
  653. That is, E consists of all zeros except for a run of 1s somewhere
  654. inside. This can be recast as E=(10000...00)(1111111...111) where
  655. there are z zeros in the LEFT part and n ones in the RIGHT part. To
  656. catch errors of this kind, we simply set the lowest bit of G to 1.
  657. Doing this ensures that LEFT cannot be a factor of G. Then, so long as
  658. G is wider than RIGHT, the error will be detected. See Tanenbaum for a
  659. clearer explanation of this; I'm a little fuzzy on this one. Note:
  660. Tanenbaum asserts that the probability of a burst of length greater
  661. than W getting through is (0.5)^W.
  662.  
  663. That concludes the section on the fine art of selecting polys.
  664.  
  665. Some popular polys are:
  666. 16 bits: (16,12,5,0)                                [X25 standard]
  667.          (16,15,2,0)                                ["CRC-16"]
  668. 32 bits: (32,26,23,22,16,12,11,10,8,7,5,4,2,1,0)    [Ethernet]
  669.  
  670. 8. A Straightforward CRC Implementation
  671. ---------------------------------------
  672. That's the end of the theory; now we turn to implementations. To start
  673. with, we examine an absolutely straight-down-the-middle boring
  674. straightforward low-speed implementation that doesn't use any speed
  675. tricks at all. We'll then transform that program progessively until we
  676. end up with the compact table-driven code we all know and love and
  677. which some of us would like to understand.
  678.  
  679. To implement a CRC algorithm all we have to do is implement CRC
  680. division. There are two reasons why we cannot simply use the divide
  681. instruction of whatever machine we are on. The first is that we have
  682. to do the divide in CRC arithmetic. The second is that the dividend
  683. might be ten megabytes long, and todays processors do not have
  684. registers that big.
  685.  
  686. So to implement CRC division, we have to feed the message through a
  687. division register. At this point, we have to be absolutely precise
  688. about the message data. In all the following examples the message will
  689. be considered to be a stream of bytes (each of 8 bits) with bit 7 of
  690. each byte being considered to be the most significant bit (MSB). The
  691. bit stream formed from these bytes will be the bit stream with the MSB
  692. (bit 7) of the first byte first, going down to bit 0 of the first
  693. byte, and then the MSB of the second byte and so on.
  694.  
  695. With this in mind, we can sketch an implementation of the CRC
  696. division. For the purposes of example, consider a poly with W=4 and
  697. the poly=10111. Then, the perform the division, we need to use a 4-bit
  698. register:
  699.  
  700.                   3   2   1   0   Bits
  701.                 +---+---+---+---+
  702.        Pop! <-- |   |   |   |   | <----- Augmented message
  703.                 +---+---+---+---+
  704.  
  705.              1    0   1   1   1   = The Poly
  706.  
  707. (Reminder: The augmented message is the message followed by W zero bits.)
  708.  
  709. To perform the division perform the following:
  710.  
  711.    Load the register with zero bits.
  712.    Augment the message by appending W zero bits to the end of it.
  713.    While (more message bits)
  714.       Begin
  715.       Shift the register left by one bit, reading the next bit of the
  716.          augmented message into register bit position 0.
  717.       If (a 1 bit popped out of the register during step 3)
  718.          Register = Register XOR Poly.
  719.       End
  720.    The register now contains the remainder.
  721.  
  722. (Note: In practice, the IF condition can be tested by testing the top
  723.  bit of R before performing the shift.)
  724.  
  725. We will call this algorithm "SIMPLE".
  726.  
  727. This might look a bit messy, but all we are really doing is
  728. "subtracting" various powers (i.e. shiftings) of the poly from the
  729. message until there is nothing left but the remainder. Study the
  730. manual examples of long division if you don't understand this.
  731.  
  732. It should be clear that the above algorithm will work for any width W.
  733.  
  734.  
  735. 9. A Table-Driven Implementation
  736. --------------------------------
  737. The SIMPLE algorithm above is a good starting point because it
  738. corresponds directly to the theory presented so far, and because it is
  739. so SIMPLE. However, because it operates at the bit level, it is rather
  740. awkward to code (even in C), and inefficient to execute (it has to
  741. loop once for each bit). To speed it up, we need to find a way to
  742. enable the algorithm to process the message in units larger than one
  743. bit. Candidate quantities are nibbles (4 bits), bytes (8 bits), words
  744. (16 bits) and longwords (32 bits) and higher if we can achieve it. Of
  745. these, 4 bits is best avoided because it does not correspond to a byte
  746. boundary. At the very least, any speedup should allow us to operate at
  747. byte boundaries, and in fact most of the table driven algorithms
  748. operate a byte at a time.
  749.  
  750. For the purposes of discussion, let us switch from a 4-bit poly to a
  751. 32-bit one. Our register looks much the same, except the boxes
  752. represent bytes instead of bits, and the Poly is 33 bits (one implicit
  753. 1 bit at the top and 32 "active" bits) (W=32).
  754.  
  755.                    3    2    1    0   Bytes
  756.                 +----+----+----+----+
  757.        Pop! <-- |    |    |    |    | <----- Augmented message
  758.                 +----+----+----+----+
  759.  
  760.                1<------32 bits------>
  761.  
  762. The SIMPLE algorithm is still applicable. Let us examine what it does.
  763. Imagine that the SIMPLE algorithm is in full swing and consider the
  764. top 8 bits of the 32-bit register (byte 3) to have the values:
  765.  
  766.    t7 t6 t5 t4 t3 t2 t1 t0
  767.  
  768. In the next iteration of SIMPLE, t7 will determine whether the Poly
  769. will be XORed into the entire register. If t7=1, this will happen,
  770. otherwise it will not. Suppose that the top 8 bits of the poly are g7
  771. g6.. g0, then after the next iteration, the top byte will be:
  772.  
  773.         t6 t5 t4 t3 t2 t1 t0 ??
  774. + t7 * (g7 g6 g5 g4 g3 g2 g1 g0)    [Reminder: + is XOR]
  775.  
  776. The NEW top bit (that will control what happens in the next iteration)
  777. now has the value t6 + t7*g7. The important thing to notice here is
  778. that from an informational point of view, all the information required
  779. to calculate the NEW top bit was present in the top TWO bits of the
  780. original top byte. Similarly, the NEXT top bit can be calculated in
  781. advance SOLELY from the top THREE bits t7, t6, and t5. In fact, in
  782. general, the value of the top bit in the register in k iterations can
  783. be calculated from the top k bits of the register. Let us take this
  784. for granted for a moment.
  785.  
  786. Consider for a moment that we use the top 8 bits of the register to
  787. calculate the value of the top bit of the register during the next 8
  788. iterations. Suppose that we drive the next 8 iterations using the
  789. calculated values (which we could perhaps store in a single byte
  790. register and shift out to pick off each bit). Then we note three
  791. things:
  792.  
  793.    * The top byte of the register now doesn't matter. No matter how
  794.      many times and at what offset the poly is XORed to the top 8
  795.      bits, they will all be shifted out the right hand side during the
  796.      next 8 iterations anyway.
  797.  
  798.  
  799.    * The remaining bits will be shifted left one position and the
  800.      rightmost byte of the register will be shifted in the next byte
  801.  
  802.    AND
  803.  
  804.    * While all this is going on, the register will be subjected to a
  805.      series of XOR's in accordance with the bits of the pre-calculated
  806.      control byte.
  807.  
  808. Now consider the effect of XORing in a constant value at various
  809. offsets to a register. For example:
  810.  
  811.        0100010  Register
  812.        ...0110  XOR this
  813.        ..0110.  XOR this
  814.        0110...  XOR this
  815.        -------
  816.        0011000
  817.        -------
  818.  
  819. The point of this is that you can XOR constant values into a register
  820. to your heart's delight, and in the end, there will exist a value
  821. which when XORed in with the original register will have the same
  822. effect as all the other XORs.
  823.  
  824. Perhaps you can see the solution now. Putting all the pieces together
  825. we have an algorithm that goes like this:
  826.  
  827.    While (augmented message is not exhausted)
  828.       Begin
  829.       Examine the top byte of the register
  830.       Calculate the control byte from the top byte of the register
  831.       Sum all the Polys at various offsets that are to be XORed into
  832.          the register in accordance with the control byte
  833.       Shift the register left by one byte, reading a new message byte
  834.          into the rightmost byte of the register
  835.       XOR the summed polys to the register
  836.       End
  837.  
  838. As it stands this is not much better than the SIMPLE algorithm.
  839. However, it turns out that most of the calculation can be precomputed
  840. and assembled into a table. As a result, the above algorithm can be
  841. reduced to:
  842.  
  843.    While (augmented message is not exhaused)
  844.       Begin
  845.       Top = top_byte(Register);
  846.       Register = (Register << 24) | next_augmessage_byte;
  847.       Register = Register XOR precomputed_table[Top];
  848.       End
  849.  
  850. There! If you understand this, you've grasped the main idea of
  851. table-driven CRC algorithms. The above is a very efficient algorithm
  852. requiring just a shift, and OR, an XOR, and a table lookup per byte.
  853. Graphically, it looks like this:
  854.  
  855.                    3    2    1    0   Bytes
  856.                 +----+----+----+----+
  857.          +-----<|    |    |    |    | <----- Augmented message
  858.          |      +----+----+----+----+
  859.          |                ^
  860.          |                |
  861.          |               XOR
  862.          |                |
  863.          |     0+----+----+----+----+       Algorithm
  864.          v      +----+----+----+----+       ---------
  865.          |      +----+----+----+----+       1. Shift the register left by
  866.          |      +----+----+----+----+          one byte, reading in a new
  867.          |      +----+----+----+----+          message byte.
  868.          |      +----+----+----+----+       2. Use the top byte just rotated
  869.          |      +----+----+----+----+          out of the register to index
  870.          +----->+----+----+----+----+          the table of 256 32-bit values.
  871.                 +----+----+----+----+       3. XOR the table value into the
  872.                 +----+----+----+----+          register.
  873.                 +----+----+----+----+       4. Goto 1 iff more augmented
  874.                 +----+----+----+----+          message bytes.
  875.              255+----+----+----+----+
  876.  
  877.  
  878. In C, the algorithm main loop looks like this:
  879.  
  880.    r=0;
  881.    while (len--)
  882.      {
  883.       byte t = (r >> 24) & 0xFF;
  884.       r = (r << 8) | *p++;
  885.       r^=table[t];
  886.      }
  887.  
  888. where len is the length of the augmented message in bytes, p points to
  889. the augmented message, r is the register, t is a temporary, and table
  890. is the computed table. This code can be made even more unreadable as
  891. follows:
  892.  
  893.    r=0; while (len--) r = ((r << 8) | *p++) ^ t[(r >> 24) & 0xFF];
  894.  
  895. This is a very clean, efficient loop, although not a very obvious one
  896. to the casual observer not versed in CRC theory. We will call this the
  897. TABLE algorithm.
  898.  
  899. 10. A Slightly Mangled Table-Driven Implementation
  900. --------------------------------------------------
  901. Despite the terse beauty of the line
  902.  
  903.    r=0; while (len--) r = ((r << 8) | *p++) ^ t[(r >> 24) & 0xFF];
  904.  
  905. those optimizing hackers couldn't leave it alone. The trouble, you
  906. see, is that this loop operates upon the AUGMENTED message and in
  907. order to use this code, you have to append W/8 zero bytes to the end
  908. of the message before pointing p at it. Depending on the run-time
  909. environment, this may or may not be a problem; if the block of data
  910. was handed to us by some other code, it could be a BIG problem. One
  911. alternative is simply to append the following line after the above
  912. loop, once for each zero byte:
  913.  
  914.       for (i=0; i<W/4; i++) r = (r << 8) ^ t[(r >> 24) & 0xFF];
  915.  
  916. This looks like a sane enough solution to me. However, at the further
  917. expense of clarity (which, you must admit, is already a pretty scare
  918. commodity in this code) we can reorganize this small loop further so
  919. as to avoid the need to either augment the message with zero bytes, or
  920. to explicitly process zero bytes at the end as above. To explain the
  921. optimization, we return to the processing diagram given earlier.
  922.  
  923.                    3    2    1    0   Bytes
  924.                 +----+----+----+----+
  925.          +-----<|    |    |    |    | <----- Augmented message
  926.          |      +----+----+----+----+
  927.          |                ^
  928.          |                |
  929.          |               XOR
  930.          |                |
  931.          |     0+----+----+----+----+       Algorithm
  932.          v      +----+----+----+----+       ---------
  933.          |      +----+----+----+----+       1. Shift the register left by
  934.          |      +----+----+----+----+          one byte, reading in a new
  935.          |      +----+----+----+----+          message byte.
  936.          |      +----+----+----+----+       2. Use the top byte just rotated
  937.          |      +----+----+----+----+          out of the register to index
  938.          +----->+----+----+----+----+          the table of 256 32-bit values.
  939.                 +----+----+----+----+       3. XOR the table value into the
  940.                 +----+----+----+----+          register.
  941.                 +----+----+----+----+       4. Goto 1 iff more augmented
  942.                 +----+----+----+----+          message bytes.
  943.              255+----+----+----+----+
  944.  
  945. Now, note the following facts:
  946.  
  947. TAIL: The W/4 augmented zero bytes that appear at the end of the
  948.       message will be pushed into the register from the right as all
  949.       the other bytes are, but their values (0) will have no effect
  950.       whatsoever on the register because 1) XORing with zero does not
  951.       change the target byte, and 2) the four bytes are never
  952.       propagated out the left side of the register where their
  953.       zeroness might have some sort of influence. Thus, the sole
  954.       function of the W/4 augmented zero bytes is to drive the
  955.       calculation for another W/4 byte cycles so that the end of the
  956.       REAL data passes all the way through the register.
  957.  
  958. HEAD: If the initial value of the register is zero, the first four
  959.       iterations of the loop will have the sole effect of shifting in
  960.       the first four bytes of the message from the right. This is
  961.       because the first 32 control bits are all zero and so nothing is
  962.       XORed into the register. Even if the initial value is not zero,
  963.       the first 4 byte iterations of the algorithm will have the sole
  964.       effect of shifting the first 4 bytes of the message into the
  965.       register and then XORing them with some constant value (that is
  966.       a function of the initial value of the register).
  967.  
  968. These facts, combined with the XOR property
  969.  
  970.    (A xor B) xor C = A xor (B xor C)
  971.  
  972. mean that message bytes need not actually travel through the W/4 bytes
  973. of the register. Instead, they can be XORed into the top byte just
  974. before it is used to index the lookup table. This leads to the
  975. following modified version of the algorithm.
  976.  
  977.  
  978.          +-----<Message (non augmented)
  979.          |
  980.          v         3    2    1    0   Bytes
  981.          |      +----+----+----+----+
  982.         XOR----<|    |    |    |    |
  983.          |      +----+----+----+----+
  984.          |                ^
  985.          |                |
  986.          |               XOR
  987.          |                |
  988.          |     0+----+----+----+----+       Algorithm
  989.          v      +----+----+----+----+       ---------
  990.          |      +----+----+----+----+       1. Shift the register left by
  991.          |      +----+----+----+----+          one byte, reading in a new
  992.          |      +----+----+----+----+          message byte.
  993.          |      +----+----+----+----+       2. XOR the top byte just rotated
  994.          |      +----+----+----+----+          out of the register with the
  995.          +----->+----+----+----+----+          next message byte to yield an
  996.                 +----+----+----+----+          index into the table ([0,255]).
  997.                 +----+----+----+----+       3. XOR the table value into the
  998.                 +----+----+----+----+          register.
  999.                 +----+----+----+----+       4. Goto 1 iff more augmented
  1000.              255+----+----+----+----+          message bytes.
  1001.  
  1002.  
  1003. Note: The initial register value for this algorithm must be the
  1004. initial value of the register for the previous algorithm fed through
  1005. the table four times. Note: The table is such that if the previous
  1006. algorithm used 0, the new algorithm will too.
  1007.  
  1008. This is an IDENTICAL algorithm and will yield IDENTICAL results. The C
  1009. code looks something like this:
  1010.  
  1011.    r=0; while (len--) r = (r<<8) ^ t[(r >> 24) ^ *p++];
  1012.  
  1013. and THIS is the code that you are likely to find inside current
  1014. table-driven CRC implementations. Some FF masks might have to be ANDed
  1015. in here and there for portability's sake, but basically, the above
  1016. loop is IT. We will call this the DIRECT TABLE ALGORITHM.
  1017.  
  1018. During the process of trying to understand all this stuff, I managed
  1019. to derive the SIMPLE algorithm and the table-driven version derived
  1020. from that. However, when I compared my code with the code found in
  1021. real-implementations, I was totally bamboozled as to why the bytes
  1022. were being XORed in at the wrong end of the register! It took quite a
  1023. while before I figured out that theirs and my algorithms were actually
  1024. the same. Part of why I am writing this document is that, while the
  1025. link between division and my earlier table-driven code is vaguely
  1026. apparent, any such link is fairly well erased when you start pumping
  1027. bytes in at the "wrong end" of the register. It looks all wrong!
  1028.  
  1029. If you've got this far, you not only understand the theory, the
  1030. practice, the optimized practice, but you also understand the real
  1031. code you are likely to run into. Could get any more complicated? Yes
  1032. it can.
  1033.  
  1034.  
  1035. 11. "Reflected" Table-Driven Implementations
  1036. --------------------------------------------
  1037. Despite the fact that the above code is probably optimized about as
  1038. much as it could be, this did not stop some enterprising individuals
  1039. from making things even more complicated. To understand how this
  1040. happened, we have to enter the world of hardware.
  1041.  
  1042. DEFINITION: A value/register is reflected if it's bits are swapped
  1043. around its centre. For example: 0101 is the 4-bit reflection of 1010.
  1044. 0011 is the reflection of 1100.
  1045. 0111-0101-1010-1111-0010-0101-1011-1100 is the reflection of
  1046. 0011-1101-1010-0100-1111-0101-1010-1110.
  1047.  
  1048. Turns out that UARTs (those handy little chips that perform serial IO)
  1049. are in the habit of transmitting each byte with the least significant
  1050. bit (bit 0) first and the most significant bit (bit 7) last (i.e.
  1051. reflected). An effect of this convention is that hardware engineers
  1052. constructing hardware CRC calculators that operate at the bit level
  1053. took to calculating CRCs of bytes streams with each of the bytes
  1054. reflected within itself. The bytes are processed in the same order,
  1055. but the bits in each byte are swapped; bit 0 is now bit 7, bit 1 is
  1056. now bit 6, and so on. Now this wouldn't matter much if this convention
  1057. was restricted to hardware land. However it seems that at some stage
  1058. some of these CRC values were presented at the software level and
  1059. someone had to write some code that would interoperate with the
  1060. hardware CRC calculation.
  1061.  
  1062. In this situation, a normal sane software engineer would simply
  1063. reflect each byte before processing it. However, it would seem that
  1064. normal sane software engineers were thin on the ground when this early
  1065. ground was being broken, because instead of reflecting the bytes,
  1066. whoever was responsible held down the byte and reflected the world,
  1067. leading to the following "reflected" algorithm which is identical to
  1068. the previous one except that everything is reflected except the input
  1069. bytes.
  1070.  
  1071.  
  1072.              Message (non augmented) >-----+
  1073.                                            |
  1074.            Bytes   0    1    2    3        v
  1075.                 +----+----+----+----+      |
  1076.                 |    |    |    |    |>----XOR
  1077.                 +----+----+----+----+      |
  1078.                           ^                |
  1079.                           |                |
  1080.                          XOR               |
  1081.                           |                |
  1082.                 +----+----+----+----+0     |
  1083.                 +----+----+----+----+      v
  1084.                 +----+----+----+----+      |
  1085.                 +----+----+----+----+      |
  1086.                 +----+----+----+----+      |
  1087.                 +----+----+----+----+      |
  1088.                 +----+----+----+----+      |
  1089.                 +----+----+----+----+<-----+
  1090.                 +----+----+----+----+
  1091.                 +----+----+----+----+
  1092.                 +----+----+----+----+
  1093.                 +----+----+----+----+
  1094.                 +----+----+----+----+255
  1095.  
  1096. Notes:
  1097.  
  1098.    * The table is identical to the one in the previous algorithm
  1099.    except that each entry has been reflected.
  1100.  
  1101.    * The initial value of the register is the same as in the previous
  1102.    algorithm except that it has been reflected.
  1103.  
  1104.    * The bytes of the message are processed in the same order as
  1105.    before (i.e. the message itself is not reflected).
  1106.  
  1107.    * The message bytes themselves don't need to be explicitly
  1108.    reflected, because everything else has been!
  1109.  
  1110. At the end of execution, the register contains the reflection of the
  1111. final CRC value (remainder). Actually, I'm being rather hard on
  1112. whoever cooked this up because it seems that hardware implementations
  1113. of the CRC algorithm used the reflected checksum value and so
  1114. producing a reflected CRC was just right. In fact reflecting the world
  1115. was probably a good engineering solution - if a confusing one.
  1116.  
  1117. We will call this the REFLECTED algorithm.
  1118.  
  1119. Whether or not it made sense at the time, the effect of having
  1120. reflected algorithms kicking around the world's FTP sites is that
  1121. about half the CRC implementations one runs into are reflected and the
  1122. other half not. It's really terribly confusing. In particular, it
  1123. would seem to me that the casual reader who runs into a reflected,
  1124. table-driven implementation with the bytes "fed in the wrong end"
  1125. would have Buckley's chance of ever connecting the code to the concept
  1126. of binary mod 2 division.
  1127.  
  1128. It couldn't get any more confusing could it? Yes it could.
  1129. 12. "Reversed" Polys
  1130. --------------------
  1131. As if reflected implementations weren't enough, there is another
  1132. concept kicking around which makes the situation bizaarly confusing.
  1133. The concept is reversed Polys.
  1134.  
  1135. It turns out that the reflection of good polys tend to be good polys
  1136. too! That is, if G=11101 is a good poly value, then 10111 will be as
  1137. well. As a consequence, it seems that every time an organization (such
  1138. as CCITT) standardizes on a particularly good poly ("polynomial"),
  1139. those in the real world can't leave the poly's reflection alone
  1140. either. They just HAVE to use it. As a result, the set of "standard"
  1141. poly's has a corresponding set of reflections, which are also in use.
  1142. To avoid confusion, we will call these the "reversed" polys.
  1143.  
  1144.    X25   standard: 1-0001-0000-0010-0001
  1145.    X25   reversed: 1-0000-1000-0001-0001
  1146.  
  1147.    CRC16 standard: 1-1000-0000-0000-0101
  1148.    CRC16 reversed: 1-0100-0000-0000-0011
  1149.  
  1150. Note that here it is the entire poly that is being reflected/reversed,
  1151. not just the bottom W bits. This is an important distinction. In the
  1152. reflected algorithm described in the previous section, the poly used
  1153. in the reflected algorithm was actually identical to that used in the
  1154. non-reflected algorithm; all that had happened is that the bytes had
  1155. effectively been reflected. As such, all the 16-bit/32-bit numbers in
  1156. the algorithm had to be reflected. In contrast, the ENTIRE poly
  1157. includes the implicit one bit at the top, and so reversing a poly is
  1158. not the same as reflecting its bottom 16 or 32 bits.
  1159.  
  1160. The upshot of all this is that a reflected algorithm is not equivalent
  1161. to the original algorithm with the poly reflected. Actually, this is
  1162. probably less confusing than if they were duals.
  1163.  
  1164. If all this seems a bit unclear, don't worry, because we're going to
  1165. sort it all out "real soon now". Just one more section to go before
  1166. that.
  1167.  
  1168.  
  1169. 13. Initial and Final Values
  1170. ----------------------------
  1171. In addition to the complexity already seen, CRC algorithms differ from
  1172. each other in two other regards:
  1173.  
  1174.    * The initial value of the register.
  1175.  
  1176.    * The value to be XORed with the final register value.
  1177.  
  1178. For example, the "CRC32" algorithm initializes its register to
  1179. FFFFFFFF and XORs the final register value with FFFFFFFF.
  1180.  
  1181. Most CRC algorithms initialize their register to zero. However, some
  1182. initialize it to a non-zero value. In theory (i.e. with no assumptions
  1183. about the message), the initial value has no affect on the strength of
  1184. the CRC algorithm, the initial value merely providing a fixed starting
  1185. point from which the register value can progress. However, in
  1186. practice, some messages are more likely than others, and it is wise to
  1187. initialize the CRC algorithm register to a value that does not have
  1188. "blind spots" that are likely to occur in practice. By "blind spot" is
  1189. meant a sequence of message bytes that do not result in the register
  1190. changing its value. In particular, any CRC algorithm that initializes
  1191. its register to zero will have a blind spot of zero when it starts up
  1192. and will be unable to "count" a leading run of zero bytes. As a
  1193. leading run of zero bytes is quite common in real messages, it is wise
  1194. to initialize the algorithm register to a non-zero value.
  1195.  
  1196.  
  1197. 14. Defining Algorithms Absolutely
  1198. ----------------------------------
  1199. At this point we have covered all the different aspects of
  1200. table-driven CRC algorithms. As there are so many variations on these
  1201. algorithms, it is worth trying to establish a nomenclature for them.
  1202. This section attempts to do that.
  1203.  
  1204. We have seen that CRC algorithms vary in:
  1205.  
  1206.    * Width of the poly (polynomial).
  1207.    * Value of the poly.
  1208.    * Initial value for the register.
  1209.    * Whether the bits of each byte are reflected before being processed.
  1210.    * Whether the algorithm feeds input bytes through the register or
  1211.      xors them with a byte from one end and then straight into the table.
  1212.    * Whether the final register value should be reversed (as in reflected
  1213.      versions).
  1214.    * Value to XOR with the final register value.
  1215.  
  1216. In order to be able to talk about particular CRC algorithms, we need
  1217. to able to define them more precisely than this. For this reason, the
  1218. next section attempts to provide a well-defined parameterized model
  1219. for CRC algorithms. To refer to a particular algorithm, we need then
  1220. simply specify the algorithm in terms of parameters to the model.
  1221.  
  1222.  
  1223. 15. A Parameterized Model For CRC Algorithms
  1224. --------------------------------------------
  1225. In this section we define a precise parameterized model CRC algorithm
  1226. which, for want of a better name, we will call the "Rocksoft^tm Model
  1227. CRC Algorithm" (and why not? Rocksoft^tm could do with some free
  1228. advertising :-).
  1229.  
  1230. The most important aspect of the model algorithm is that it focusses
  1231. exclusively on functionality, ignoring all implementation details. The
  1232. aim of the exercise is to construct a way of referring precisely to
  1233. particular CRC algorithms, regardless of how confusingly they are
  1234. implemented. To this end, the model must be as simple and precise as
  1235. possible, with as little confusion as possible.
  1236.  
  1237. The Rocksoft^tm Model CRC Algorithm is based essentially on the DIRECT
  1238. TABLE ALGORITHM specified earlier. However, the algorithm has to be
  1239. further parameterized to enable it to behave in the same way as some
  1240. of the messier algorithms out in the real world.
  1241.  
  1242. To enable the algorithm to behave like reflected algorithms, we
  1243. provide a boolean option to reflect the input bytes, and a boolean
  1244. option to specify whether to reflect the output checksum value. By
  1245. framing reflection as an input/output transformation, we avoid the
  1246. confusion of having to mentally map the parameters of reflected and
  1247. non-reflected algorithms.
  1248.  
  1249. An extra parameter allows the algorithm's register to be initialized
  1250. to a particular value. A further parameter is XORed with the final
  1251. value before it is returned.
  1252.  
  1253. By putting all these pieces together we end up with the parameters of
  1254. the algorithm:
  1255.  
  1256.    NAME: This is a name given to the algorithm. A string value.
  1257.  
  1258.    WIDTH: This is the width of the algorithm expressed in bits. This
  1259.    is one less than the width of the Poly.
  1260.  
  1261.    POLY: This parameter is the poly. This is a binary value that
  1262.    should be specified as a hexadecimal number. The top bit of the
  1263.    poly should be omitted. For example, if the poly is 10110, you
  1264.    should specify 06. An important aspect of this parameter is that it
  1265.    represents the unreflected poly; the bottom bit of this parameter
  1266.    is always the LSB of the divisor during the division regardless of
  1267.    whether the algorithm being modelled is reflected.
  1268.  
  1269.    INIT: This parameter specifies the initial value of the register
  1270.    when the algorithm starts. This is the value that is to be assigned
  1271.    to the register in the direct table algorithm. In the table
  1272.    algorithm, we may think of the register always commencing with the
  1273.    value zero, and this value being XORed into the register after the
  1274.    N'th bit iteration. This parameter should be specified as a
  1275.    hexadecimal number.
  1276.  
  1277.    REFIN: This is a boolean parameter. If it is FALSE, input bytes are
  1278.    processed with bit 7 being treated as the most significant bit
  1279.    (MSB) and bit 0 being treated as the least significant bit. If this
  1280.    parameter is FALSE, each byte is reflected before being processed.
  1281.  
  1282.    REFOUT: This is a boolean parameter. If it is set to FALSE, the
  1283.    final value in the register is fed into the XOROUT stage directly,
  1284.    otherwise, if this parameter is TRUE, the final register value is
  1285.    reflected first.
  1286.  
  1287.    XOROUT: This is an W-bit value that should be specified as a
  1288.    hexadecimal number. It is XORed to the final register value (after
  1289.    the REFOUT) stage before the value is returned as the official
  1290.    checksum.
  1291.  
  1292.    CHECK: This field is not strictly part of the definition, and, in
  1293.    the event of an inconsistency between this field and the other
  1294.    field, the other fields take precedence. This field is a check
  1295.    value that can be used as a weak validator of implementations of
  1296.    the algorithm. The field contains the checksum obtained when the
  1297.    ASCII string "123456789" is fed through the specified algorithm
  1298.    (i.e. 313233... (hexadecimal)).
  1299.  
  1300. With these parameters defined, the model can now be used to specify a
  1301. particular CRC algorithm exactly. Here is an example specification for
  1302. a popular form of the CRC-16 algorithm.
  1303.  
  1304.    Name   : "CRC-16"
  1305.    Width  : 16
  1306.    Poly   : 8005
  1307.    Init   : 0000
  1308.    RefIn  : True
  1309.    RefOut : True
  1310.    XorOut : 0000
  1311.    Check  : BB3D
  1312.  
  1313. 16. A Catalog of Parameter Sets for Standards
  1314. ---------------------------------------------
  1315. At this point, I would like to give a list of the specifications for
  1316. commonly used CRC algorithms. However, most of the algorithms that I
  1317. have come into contact with so far are specified in such a vague way
  1318. that this has not been possible. What I can provide is a list of polys
  1319. for various CRC standards I have heard of:
  1320.  
  1321.    X25   standard : 1021       [CRC-CCITT, ADCCP, SDLC/HDLC]
  1322.    X25   reversed : 0811
  1323.  
  1324.    CRC16 standard : 8005
  1325.    CRC16 reversed : 4003       [LHA]
  1326.  
  1327.    CRC32          : 04C11DB7   [PKZIP, AUTODIN II, Ethernet, FDDI]
  1328.  
  1329. I would be interested in hearing from anyone out there who can tie
  1330. down the complete set of model parameters for any of these standards.
  1331.  
  1332. However, a program that was kicking around seemed to imply the
  1333. following specifications. Can anyone confirm or deny them (or provide
  1334. the check values (which I couldn't be bothered coding up and
  1335. calculating)).
  1336.  
  1337.    Name   : "CRC-16/CITT"
  1338.    Width  : 16
  1339.    Poly   : 1021
  1340.    Init   : FFFF
  1341.    RefIn  : False
  1342.    RefOut : False
  1343.    XorOut : 0000
  1344.    Check  : ?
  1345.  
  1346.  
  1347.    Name   : "XMODEM"
  1348.    Width  : 16
  1349.    Poly   : 8408
  1350.    Init   : 0000
  1351.    RefIn  : True
  1352.    RefOut : True
  1353.    XorOut : 0000
  1354.    Check  : ?
  1355.  
  1356.  
  1357.    Name   : "ARC"
  1358.    Width  : 16
  1359.    Poly   : 8005
  1360.    Init   : 0000
  1361.    RefIn  : True
  1362.    RefOut : True
  1363.    XorOut : 0000
  1364.    Check  : ?
  1365.  
  1366. Here is the specification for the CRC-32 algorithm which is reportedly
  1367. used in PKZip, AUTODIN II, Ethernet, and FDDI.
  1368.  
  1369.    Name   : "CRC-32"
  1370.    Width  : 32
  1371.    Poly   : 04C11DB7
  1372.    Init   : FFFFFFFF
  1373.    RefIn  : True
  1374.    RefOut : True
  1375.    XorOut : FFFFFFFF
  1376.    Check  : CBF43926
  1377.  
  1378.  
  1379. 17. An Implementation of the Model Algorithm
  1380. --------------------------------------------
  1381. Here is an implementation of the model algorithm in the C programming
  1382. language. The implementation consists of a header file (.h) and an
  1383. implementation file (.c). If you're reading this document in a
  1384. sequential scroller, you can skip this code by searching for the
  1385. string "Roll Your Own".
  1386.  
  1387. To ensure that the following code is working, configure it for the
  1388. CRC-16 and CRC-32 algorithms given above and ensure that they produce
  1389. the specified "check" checksum when fed the test string "123456789"
  1390. (see earlier).
  1391.  
  1392. /****************************************************************************/
  1393. /*                             Start of crcmodel.h                          */
  1394. /****************************************************************************/
  1395. /*                                                                          */
  1396. /* Author : Ross Williams (ross@guest.adelaide.edu.au.).                    */
  1397. /* Date   : 3 June 1993.                                                    */
  1398. /* Status : Public domain.                                                  */
  1399. /*                                                                          */
  1400. /* Description : This is the header (.h) file for the reference             */
  1401. /* implementation of the Rocksoft^tm Model CRC Algorithm. For more          */
  1402. /* information on the Rocksoft^tm Model CRC Algorithm, see the document     */
  1403. /* titled "A Painless Guide to CRC Error Detection Algorithms" by Ross      */
  1404. /* Williams (ross@guest.adelaide.edu.au.). This document is likely to be in */
  1405. /* "ftp.adelaide.edu.au/pub/rocksoft".                                      */
  1406. /*                                                                          */
  1407. /* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.  */
  1408. /*                                                                          */
  1409. /****************************************************************************/
  1410. /*                                                                          */
  1411. /* How to Use This Package                                                  */
  1412. /* -----------------------                                                  */
  1413. /* Step 1: Declare a variable of type cm_t. Declare another variable        */
  1414. /*         (p_cm say) of type p_cm_t and initialize it to point to the first*/
  1415. /*         variable (e.g. p_cm_t p_cm = &cm_t).                             */
  1416. /*                                                                          */
  1417. /* Step 2: Assign values to the parameter fields of the structure.          */
  1418. /*         If you don't know what to assign, see the document cited earlier.*/
  1419. /*         For example:                                                     */
  1420. /*            p_cm->cm_width = 16;                                          */
  1421. /*            p_cm->cm_poly  = 0x8005L;                                     */
  1422. /*            p_cm->cm_init  = 0L;                                          */
  1423. /*            p_cm->cm_refin = TRUE;                                        */
  1424. /*            p_cm->cm_refot = TRUE;                                        */
  1425. /*            p_cm->cm_xorot = 0L;                                          */
  1426. /*         Note: Poly is specified without its top bit (18005 becomes 8005).*/
  1427. /*         Note: Width is one bit less than the raw poly width.             */
  1428. /*                                                                          */
  1429. /* Step 3: Initialize the instance with a call cm_ini(p_cm);                */
  1430. /*                                                                          */
  1431. /* Step 4: Process zero or more message bytes by placing zero or more       */
  1432. /*         successive calls to cm_nxt. Example: cm_nxt(p_cm,ch);            */
  1433. /*                                                                          */
  1434. /* Step 5: Extract the CRC value at any time by calling crc = cm_crc(p_cm); */
  1435. /*         If the CRC is a 16-bit value, it will be in the bottom 16 bits.  */
  1436. /*                                                                          */
  1437. /****************************************************************************/
  1438. /*                                                                          */
  1439. /* Design Notes                                                             */
  1440. /* ------------                                                             */
  1441. /* PORTABILITY: This package has been coded very conservatively so that     */
  1442. /* it will run on as many machines as possible. For example, all external   */
  1443. /* identifiers have been restricted to 6 characters and all internal ones to*/
  1444. /* 8 characters. The prefix cm (for Crc Model) is used as an attempt to     */
  1445. /* avoid namespace collisions. This package is endian independent.          */
  1446. /*                                                                          */
  1447. /* EFFICIENCY: This package (and its interface) is not designed for         */
  1448. /* speed. The purpose of this package is to act as a well-defined reference */
  1449. /* model for the specification of CRC algorithms. If you want speed, cook up*/
  1450. /* a specific table-driven implementation as described in the document cited*/
  1451. /* above. This package is designed for validation only; if you have found or*/
  1452. /* implemented a CRC algorithm and wish to describe it as a set of para-    */
  1453. /* meters to the Rocksoft^tm Model CRC Algorithm, your CRC algorithm imple- */
  1454. /* mentation should behave identically to this package under those para-    */
  1455. /* meters.                                                                  */
  1456. /*                                                                          */
  1457. /****************************************************************************/
  1458.  
  1459. /* The following #ifndef encloses this entire */
  1460. /* header file, rendering it indempotent.     */
  1461.  
  1462. #ifndef CM_DONE
  1463. #define CM_DONE
  1464.  
  1465. /****************************************************************************/
  1466. /* The following definitions are extracted from my style header file which  */
  1467. /* would be cumbersome to distribute with this package. The DONE_STYLE is   */
  1468. /* the idempotence symbol used in my style header file.                     */
  1469.  
  1470. #ifndef DONE_STYLE
  1471.  
  1472. typedef unsigned long   ulong;
  1473. typedef unsigned        bool;
  1474. typedef unsigned char * p_ubyte_;
  1475.  
  1476. #ifndef TRUE
  1477. #define FALSE 0
  1478. #define TRUE  1
  1479. #endif
  1480.  
  1481. /* Change to the second definition if you don't have prototypes. */
  1482. #define P_(A) A
  1483. /* #define P_(A) () */
  1484.  
  1485. /* Uncomment this definition if you don't have void. */
  1486. /* typedef int void; */
  1487.  
  1488. #endif
  1489.  
  1490. /****************************************************************************/
  1491. /* CRC Model Abstract Type                                                  */
  1492. /* -----------------------                                                  */
  1493. /* The following type stores the context of an executing instance of the    */
  1494. /* model algorithm. Most of the fields are model parameters which must be   */
  1495. /* set before the first initializing call to cm_ini.                        */
  1496.  
  1497. typedef struct
  1498.   {
  1499.    int   cm_width;   /* Parameter: Width in bits [8,32].       */
  1500.    ulong cm_poly;    /* Parameter: The algorithm's polynomial. */
  1501.    ulong cm_init;    /* Parameter: Initial register value.     */
  1502.    bool  cm_refin;   /* Parameter: Reflect input bytes?        */
  1503.    bool  cm_refot;   /* Parameter: Reflect output CRC?         */
  1504.    ulong cm_xorot;   /* Parameter: XOR this to output CRC.     */
  1505.  
  1506.    ulong cm_reg;     /* Context: Context during execution.     */
  1507.   } cm_t;
  1508. typedef cm_t *p_cm_t;
  1509.  
  1510. /****************************************************************************/
  1511. /* Functions That Implement The Model                                       */
  1512. /* ----------------------------------                                       */
  1513. /* The following functions animate the cm_t abstraction.                    */
  1514.  
  1515. void cm_ini P_((p_cm_t p_cm));
  1516.  
  1517. /* Initializes the argument CRC model instance.          */
  1518. /* All parameter fields must be set before calling this. */
  1519.  
  1520. void cm_nxt P_((p_cm_t p_cm,int ch));
  1521.  
  1522. /* Processes a single message byte [0,255]. */
  1523.  
  1524. void cm_blk P_((p_cm_t p_cm,p_ubyte_ blk_adr,ulong blk_len));
  1525.  
  1526. /* Processes a block of message bytes. */
  1527.  
  1528. ulong cm_crc P_((p_cm_t p_cm));
  1529.  
  1530. /* Returns the CRC value for the message bytes processed so far. */
  1531.  
  1532. /****************************************************************************/
  1533. /* Functions For Table Calculation                                          */
  1534. /* -------------------------------                                          */
  1535. /* The following function can be used to calculate a CRC lookup table.      */
  1536. /* It can also be used at run-time to create or check static tables.        */
  1537.  
  1538. ulong cm_tab P_((p_cm_t p_cm,int index));
  1539.  
  1540. /* Returns the i'th entry for the lookup table for the specified algorithm. */
  1541. /* The function examines the fields cm_width, cm_poly, cm_refin, and the    */
  1542. /* argument table index in the range [0,255] and returns the table entry in */
  1543. /* the bottom cm_width bytes of the return value. */
  1544.  
  1545. /****************************************************************************/
  1546. /* End of the header file idempotence #ifndef                               */
  1547.  
  1548. #endif
  1549.  
  1550. /****************************************************************************/
  1551. /*                             End of crcmodel.h                            */
  1552. /****************************************************************************/
  1553.  
  1554. /****************************************************************************/
  1555. /*                             Start of crcmodel.c                          */
  1556. /****************************************************************************/
  1557. /*                                                                          */
  1558. /* Author : Ross Williams (ross@guest.adelaide.edu.au.).                    */
  1559. /* Date   : 3 June 1993.                                                    */
  1560. /* Status : Public domain.                                                  */
  1561. /*                                                                          */
  1562. /* Description : This is the implementation (.c) file for the reference     */
  1563. /* implementation of the Rocksoft^tm Model CRC Algorithm. For more          */
  1564. /* information on the Rocksoft^tm Model CRC Algorithm, see the document     */
  1565. /* titled "A Painless Guide to CRC Error Detection Algorithms" by Ross      */
  1566. /* Williams (ross@guest.adelaide.edu.au.). This document is likely to be in */
  1567. /* "ftp.adelaide.edu.au/pub/rocksoft".                                      */
  1568. /*                                                                          */
  1569. /* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.  */
  1570. /*                                                                          */
  1571. /****************************************************************************/
  1572. /*                                                                          */
  1573. /* Implementation Notes                                                     */
  1574. /* --------------------                                                     */
  1575. /* To avoid inconsistencies, the specification of each function is not      */
  1576. /* echoed here. See the header file for a description of these functions.   */
  1577. /* This package is light on checking because I want to keep it short and    */
  1578. /* simple and portable (i.e. it would be too messy to distribute my entire  */
  1579. /* C culture (e.g. assertions package) with this package.                   */
  1580. /*                                                                          */
  1581. /****************************************************************************/
  1582.  
  1583. #include "crcmodel.h"
  1584.  
  1585. /****************************************************************************/
  1586. /* The following definitions make the code more readable.                   */
  1587.  
  1588. #define BITMASK(X) (1L << (X))
  1589. #define MASK32 0xFFFFFFFFL
  1590. #define LOCAL static
  1591.  
  1592. /****************************************************************************/
  1593.  
  1594. LOCAL ulong reflect P_((ulong v,int b));
  1595. LOCAL ulong reflect (v,b)
  1596.  
  1597. /* Returns the value v with the bottom b [0,32] bits reflected. */
  1598. /* Example: reflect(0x3e23L,3) == 0x3e26                        */
  1599.  
  1600. ulong v;
  1601. int   b;
  1602. {
  1603.  int   i;
  1604.  ulong t = v;
  1605.  for (i=0; i<b; i++)
  1606.    {
  1607.     if (t & 1L)
  1608.        v|=  BITMASK((b-1)-i);
  1609.     else
  1610.        v&= ~BITMASK((b-1)-i);
  1611.  
  1612.     t>>=1;
  1613.  
  1614.    }
  1615.  return v;
  1616. }
  1617.  
  1618. /****************************************************************************/
  1619.  
  1620. LOCAL ulong widmask P_((p_cm_t));
  1621. LOCAL ulong widmask (p_cm)
  1622. /* Returns a longword whose value is (2^p_cm->cm_width)-1.     */
  1623. /* The trick is to do this portably (e.g. without doing <<32). */
  1624. p_cm_t p_cm;
  1625. {
  1626.  return (((1L<<(p_cm->cm_width-1))-1L)<<1)|1L;
  1627. }
  1628.  
  1629. /****************************************************************************/
  1630.  
  1631. void cm_ini (p_cm)
  1632. p_cm_t p_cm;
  1633. {
  1634.  p_cm->cm_reg = p_cm->cm_init;
  1635. }
  1636.  
  1637. /****************************************************************************/
  1638.  
  1639. void cm_nxt (p_cm,ch)
  1640. p_cm_t p_cm;
  1641. int    ch;
  1642. {
  1643.  int   i;
  1644.  ulong uch  = (ulong) ch;
  1645.  ulong topbit = BITMASK(p_cm->cm_width-1);
  1646.  
  1647.  if (p_cm->cm_refin) uch = reflect(uch,8);
  1648.  p_cm->cm_reg ^= (uch << (p_cm->cm_width-8));
  1649.  for (i=0; i<8; i++)
  1650.    {
  1651.     if (p_cm->cm_reg & topbit)
  1652.        p_cm->cm_reg = (p_cm->cm_reg << 1) ^ p_cm->cm_poly;
  1653.     else
  1654.        p_cm->cm_reg <<= 1;
  1655.     p_cm->cm_reg &= widmask(p_cm);
  1656.    }
  1657. }
  1658.  
  1659. /****************************************************************************/
  1660.  
  1661. void cm_blk (p_cm,blk_adr,blk_len)
  1662. p_cm_t   p_cm;
  1663. p_ubyte_ blk_adr;
  1664. ulong    blk_len;
  1665. {
  1666.  while (blk_len--) cm_nxt(p_cm,*blk_adr++);
  1667. }
  1668.  
  1669. /****************************************************************************/
  1670.  
  1671. ulong cm_crc (p_cm)
  1672. p_cm_t p_cm;
  1673. {
  1674.  if (p_cm->cm_refot)
  1675.     return p_cm->cm_xorot ^ reflect(p_cm->cm_reg,p_cm->cm_width);
  1676.  else
  1677.     return p_cm->cm_xorot ^ p_cm->cm_reg;
  1678. }
  1679.  
  1680. /****************************************************************************/
  1681.  
  1682. ulong cm_tab (p_cm,index)
  1683. p_cm_t p_cm;
  1684. int    index;
  1685. {
  1686.  int   i;
  1687.  ulong r;
  1688.  ulong topbit = BITMASK(p_cm->cm_width-1);
  1689.  ulong inbyte = (ulong) index;
  1690.  
  1691.  if (p_cm->cm_refin) inbyte = reflect(inbyte,8);
  1692.  r = inbyte << (p_cm->cm_width-8);
  1693.  for (i=0; i<8; i++)
  1694.     if (r & topbit)
  1695.        r = (r << 1) ^ p_cm->cm_poly;
  1696.     else
  1697.        r<<=1;
  1698.  if (p_cm->cm_refin) r = reflect(r,p_cm->cm_width);
  1699.  return r & widmask(p_cm);
  1700. }
  1701.  
  1702. /****************************************************************************/
  1703. /*                             End of crcmodel.c                            */
  1704. /****************************************************************************/
  1705.  
  1706. 18. Roll Your Own Table-Driven Implementation
  1707. ---------------------------------------------
  1708. Despite all the fuss I've made about understanding and defining CRC
  1709. algorithms, the mechanics of their high-speed implementation remains
  1710. trivial. There are really only two forms: normal and reflected. Normal
  1711. shifts to the left and covers the case of algorithms with Refin=FALSE
  1712. and Refot=FALSE. Reflected shifts to the right and covers algorithms
  1713. with both those parameters true. (If you want one parameter true and
  1714. the other false, you'll have to figure it out for yourself!) The
  1715. polynomial is embedded in the lookup table (to be discussed). The
  1716. other parameters, Init and XorOt can be coded as macros. Here is the
  1717. 32-bit normal form (the 16-bit form is similar).
  1718.  
  1719.    unsigned long crc_normal ();
  1720.    unsigned long crc_normal (blk_adr,blk_len)
  1721.    unsigned char *blk_adr;
  1722.    unsigned long  blk_len;
  1723.    {
  1724.     unsigned long crc = INIT;
  1725.     while (blk_len--)
  1726.        crc = crctable[((crc>>24) ^ *blk_adr++) & 0xFFL] ^ (crc << 8);
  1727.     return crc ^ XOROT;
  1728.    }
  1729.  
  1730. Here is the reflected form:
  1731.  
  1732.    unsigned long crc_reflected ();
  1733.    unsigned long crc_reflected (blk_adr,blk_len)
  1734.    unsigned char *blk_adr;
  1735.    unsigned long  blk_len;
  1736.    {
  1737.     unsigned long crc = INIT_REFLECTED;
  1738.     while (blk_len--)
  1739.        crc = crctable[(crc ^ *blk_adr++) & 0xFFL] ^ (crc >> 8));
  1740.     return crc ^ XOROT;
  1741.    }
  1742.  
  1743. Note: I have carefully checked the above two code fragments, but I
  1744. haven't actually compiled or tested them. This shouldn't matter to
  1745. you, as, no matter WHAT you code, you will always be able to tell if
  1746. you have got it right by running whatever you have created against the
  1747. reference model given earlier. The code fragments above are really
  1748. just a rough guide. The reference model is the definitive guide.
  1749.  
  1750. Note: If you don't care much about speed, just use the reference model
  1751. code!
  1752.  
  1753.  
  1754. 19. Generating A Lookup Table
  1755. -----------------------------
  1756. The only component missing from the normal and reversed code fragments
  1757. in the previous section is the lookup table. The lookup table can be
  1758. computed at run time using the cm_tab function of the model package
  1759. given earlier, or can be pre-computed and inserted into the C program.
  1760. In either case, it should be noted that the lookup table depends only
  1761. on the POLY and RefIn (and RefOt) parameters. Basically, the
  1762. polynomial determines the table, but you can generate a reflected
  1763. table too if you want to use the reflected form above.
  1764.  
  1765. The following program generates any desired 16-bit or 32-bit lookup
  1766. table. Skip to the word "Summary" if you want to skip over this code.
  1767.  
  1768.  
  1769.  
  1770. /****************************************************************************/
  1771. /*                             Start of crctable.c                          */
  1772. /****************************************************************************/
  1773. /*                                                                          */
  1774. /* Author  : Ross Williams (ross@guest.adelaide.edu.au.).                   */
  1775. /* Date    : 3 June 1993.                                                   */
  1776. /* Version : 1.0.                                                           */
  1777. /* Status  : Public domain.                                                 */
  1778. /*                                                                          */
  1779. /* Description : This program writes a CRC lookup table (suitable for       */
  1780. /* inclusion in a C program) to a designated output file. The program can be*/
  1781. /* statically configured to produce any table covered by the Rocksoft^tm    */
  1782. /* Model CRC Algorithm. For more information on the Rocksoft^tm Model CRC   */
  1783. /* Algorithm, see the document titled "A Painless Guide to CRC Error        */
  1784. /* Detection Algorithms" by Ross Williams (ross@guest.adelaide.edu.au.).    */
  1785. /* This document is likely to be in "ftp.adelaide.edu.au/pub/rocksoft".     */
  1786. /*                                                                          */
  1787. /* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.  */
  1788. /*                                                                          */
  1789. /****************************************************************************/
  1790.  
  1791. #include <stdio.h>
  1792. #include <stdlib.h>
  1793. #include "crcmodel.h"
  1794.  
  1795. /****************************************************************************/
  1796. /* TABLE PARAMETERS                                                         */
  1797. /* ================                                                         */
  1798. /* The following parameters entirely determine the table to be generated.   */
  1799. /* You should need to modify only the definitions in this section before    */
  1800. /* running this program.                                                    */
  1801. /*                                                                          */
  1802. /*    TB_FILE  is the name of the output file.                              */
  1803. /*    TB_WIDTH is the table width in bytes (either 2 or 4).                 */
  1804. /*    TB_POLY  is the "polynomial", which must be TB_WIDTH bytes wide.      */
  1805. /*    TB_REVER indicates whether the table is to be reversed (reflected).   */
  1806. /*                                                                          */
  1807. /* Example:                                                                 */
  1808. /*                                                                          */
  1809. /*    #define TB_FILE   "crctable.out"                                      */
  1810. /*    #define TB_WIDTH  2                                                   */
  1811. /*    #define TB_POLY   0x8005L                                             */
  1812. /*    #define TB_REVER  TRUE                                                */
  1813.  
  1814. #define TB_FILE   "crctable.out"
  1815. #define TB_WIDTH  4
  1816. #define TB_POLY   0x04C11DB7L
  1817. #define TB_REVER  TRUE
  1818.  
  1819. /****************************************************************************/
  1820. /* Miscellaneous definitions.                                               */
  1821.  
  1822. #define LOCAL static
  1823. FILE *outfile;
  1824. #define WR(X) fprintf(outfile,(X))
  1825. #define WP(X,Y) fprintf(outfile,(X),(Y))
  1826.  
  1827. /****************************************************************************/
  1828.  
  1829. LOCAL void chk_err P_((char *));
  1830. LOCAL void chk_err (mess)
  1831.  
  1832. /* If mess is non-empty, write it out and abort. Otherwise, check the error */
  1833. /* status of outfile and abort if an error has occurred.                    */
  1834.  
  1835. char *mess;
  1836. {
  1837.  if (mess[0] != 0   ) {printf("%s\n",mess); exit(EXIT_FAILURE);}
  1838.  if (ferror(outfile)) {perror("chk_err");   exit(EXIT_FAILURE);}
  1839. }
  1840.  
  1841. /****************************************************************************/
  1842.  
  1843. LOCAL void chkparam P_((void));
  1844. LOCAL void chkparam ()
  1845. {
  1846.  if ((TB_WIDTH != 2) && (TB_WIDTH != 4))
  1847.     chk_err("chkparam: Width parameter is illegal.");
  1848.  if ((TB_WIDTH == 2) && (TB_POLY & 0xFFFF0000L))
  1849.     chk_err("chkparam: Poly parameter is too wide.");
  1850.  if ((TB_REVER != FALSE) && (TB_REVER != TRUE))
  1851.     chk_err("chkparam: Reverse parameter is not boolean.");
  1852. }
  1853.  
  1854. /****************************************************************************/
  1855.  
  1856. LOCAL void gentable P_((void));
  1857. LOCAL void gentable ()
  1858. {
  1859.  WR("/*****************************************************************/\n");
  1860.  WR("/*                                                               */\n");
  1861.  WR("/* CRC LOOKUP TABLE                                              */\n");
  1862.  WR("/* ================                                              */\n");
  1863.  WR("/* The following CRC lookup table was generated automagically    */\n");
  1864.  WR("/* by the Rocksoft^tm Model CRC Algorithm Table Generation       */\n");
  1865.  WR("/* Program V1.0 using the following model parameters:            */\n");
  1866.  WR("/*                                                               */\n");
  1867.  WP("/*    Width   : %1lu bytes.                                         */\n",
  1868.  
  1869.     (ulong) TB_WIDTH);
  1870.  if (TB_WIDTH == 2)
  1871.  WP("/*    Poly    : 0x%04lX                                           */\n",
  1872.     (ulong) TB_POLY);
  1873.  else
  1874.  WP("/*    Poly    : 0x%08lXL                                      */\n",
  1875.     (ulong) TB_POLY);
  1876.  if (TB_REVER)
  1877.  WR("/*    Reverse : TRUE.                                            */\n");
  1878.  else
  1879.  WR("/*    Reverse : FALSE.                                           */\n");
  1880.  WR("/*                                                               */\n");
  1881.  WR("/* For more information on the Rocksoft^tm Model CRC Algorithm,  */\n");
  1882.  WR("/* see the document titled \"A Painless Guide to CRC Error        */\n");
  1883.  WR("/* Detection Algorithms\" by Ross Williams                        */\n");
  1884.  WR("/* (ross@guest.adelaide.edu.au.). This document is likely to be  */\n");
  1885.  WR("/* in the FTP archive \"ftp.adelaide.edu.au/pub/rocksoft\".        */\n");
  1886.  
  1887.  WR("/*                                                               */\n");
  1888.  WR("/*****************************************************************/\n");
  1889.  WR("\n");
  1890.  switch (TB_WIDTH)
  1891.    {
  1892.     case 2: WR("unsigned short crctable[256] =\n{\n"); break;
  1893.     case 4: WR("unsigned long  crctable[256] =\n{\n"); break;
  1894.     default: chk_err("gentable: TB_WIDTH is invalid.");
  1895.    }
  1896.  chk_err("");
  1897.  
  1898.  {
  1899.   int i;
  1900.   cm_t cm;
  1901.   char *form    = (TB_WIDTH==2) ? "0x%04lX" : "0x%08lXL";
  1902.   int   perline = (TB_WIDTH==2) ? 8 : 4;
  1903.  
  1904.   cm.cm_width = TB_WIDTH*8;
  1905.   cm.cm_poly  = TB_POLY;
  1906.   cm.cm_refin = TB_REVER;
  1907.  
  1908.   for (i=0; i<256; i++)
  1909.     {
  1910.      WR(" ");
  1911.      WP(form,(ulong) cm_tab(&cm,i));
  1912.      if (i != 255) WR(",");
  1913.      if (((i+1) % perline) == 0) WR("\n");
  1914.      chk_err("");
  1915.     }
  1916.  
  1917.  WR("};\n");
  1918.  WR("\n");
  1919.  WR("/*****************************************************************/\n");
  1920.  WR("/*                   End of CRC Lookup Table                     */\n");
  1921.  WR("/*****************************************************************/\n");
  1922.  WR("");
  1923.  chk_err("");
  1924. }
  1925. }
  1926.  
  1927. /****************************************************************************/
  1928.  
  1929. main ()
  1930. {
  1931.  printf("\n");
  1932.  printf("Rocksoft^tm Model CRC Algorithm Table Generation Program V1.0\n");
  1933.  printf("-------------------------------------------------------------\n");
  1934.  printf("Output file is \"%s\".\n",TB_FILE);
  1935.  chkparam();
  1936.  outfile = fopen(TB_FILE,"w"); chk_err("");
  1937.  gentable();
  1938.  if (fclose(outfile) != 0)
  1939.     chk_err("main: Couldn't close output file.");
  1940.  printf("\nSUCCESS: The table has been successfully written.\n");
  1941. }
  1942.  
  1943. /****************************************************************************/
  1944. /*                             End of crctable.c                            */
  1945. /****************************************************************************/
  1946.  
  1947. 20. Summary
  1948. -----------
  1949. This document has provided a detailed explanation of CRC algorithms
  1950. explaining their theory and stepping through increasingly
  1951. sophisticated implementations ranging from simple bit shifting through
  1952. to byte-at-a-time table-driven implementations. The various
  1953. implementations of different CRC algorithms that make them confusing
  1954. to deal with have been explained. A parameterized model algorithm has
  1955. been described that can be used to precisely define a particular CRC
  1956. algorithm, and a reference implementation provided. Finally, a program
  1957. to generate CRC tables has been provided.
  1958.  
  1959. 21. Corrections
  1960. ---------------
  1961. If you think that any part of this document is unclear or incorrect,
  1962. or have any other information, or suggestions on how this document
  1963. could be improved, please context the author. In particular, I would
  1964. like to hear from anyone who can provide Rocksoft^tm Model CRC
  1965. Algorithm parameters for standard algorithms out there.
  1966.  
  1967. A. Glossary
  1968. -----------
  1969. CHECKSUM - A number that has been calculated as a function of some
  1970. message. The literal interpretation of this word "Check-Sum" indicates
  1971. that the function should involve simply adding up the bytes in the
  1972. message. Perhaps this was what early checksums were. Today, however,
  1973. although more sophisticated formulae are used, the term "checksum" is
  1974. still used.
  1975.  
  1976. CRC - This stands for "Cyclic Redundancy Code". Whereas the term
  1977. "checksum" seems to be used to refer to any non-cryptographic checking
  1978. information unit, the term "CRC" seems to be reserved only for
  1979. algorithms that are based on the "polynomial" division idea.
  1980.  
  1981. G - This symbol is used in this document to represent the Poly.
  1982.  
  1983. MESSAGE - The input data being checksummed. This is usually structured
  1984. as a sequence of bytes. Whether the top bit or the bottom bit of each
  1985. byte is treated as the most significant or least significant is a
  1986. parameter of CRC algorithms.
  1987.  
  1988. POLY - This is my friendly term for the polynomial of a CRC.
  1989.  
  1990. POLYNOMIAL - The "polynomial" of a CRC algorithm is simply the divisor
  1991. in the division implementing the CRC algorithm.
  1992.  
  1993. REFLECT - A binary number is reflected by swapping all of its bits
  1994. around the central point. For example, 1101 is the reflection of 1011.
  1995.  
  1996. ROCKSOFT^TM MODEL CRC ALGORITHM - A parameterized algorithm whose
  1997. purpose is to act as a solid reference for describing CRC algorithms.
  1998. Typically CRC algorithms are specified by quoting a polynomial.
  1999. However, in order to construct a precise implementation, one also
  2000. needs to know initialization values and so on.
  2001.  
  2002. WIDTH - The width of a CRC algorithm is the width of its polynomical
  2003. minus one. For example, if the polynomial is 11010, the width would be
  2004. 4 bits. The width is usually set to be a multiple of 8 bits.
  2005.  
  2006. B. References
  2007. -------------
  2008. [Griffiths87] Griffiths, G., Carlyle Stones, G., "The Tea-Leaf Reader
  2009. Algorithm: An Efficient Implementation of CRC-16 and CRC-32",
  2010. Communications of the ACM, 30(7), pp.617-620. Comment: This paper
  2011. describes a high-speed table-driven implementation of CRC algorithms.
  2012. The technique seems to be a touch messy, and is superceded by the
  2013. Sarwete algorithm.
  2014.  
  2015. [Knuth81] Knuth, D.E., "The Art of Computer Programming", Volume 2:
  2016. Seminumerical Algorithms, Section 4.6.
  2017.  
  2018. [Nelson 91] Nelson, M., "The Data Compression Book", M&T Books, (501
  2019. Galveston Drive, Redwood City, CA 94063), 1991, ISBN: 1-55851-214-4.
  2020. Comment: If you want to see a real implementation of a real 32-bit
  2021. checksum algorithm, look on pages 440, and 446-448.
  2022.  
  2023. [Sarwate88] Sarwate, D.V., "Computation of Cyclic Redundancy Checks
  2024. via Table Look-Up", Communications of the ACM, 31(8), pp.1008-1013.
  2025. Comment: This paper describes a high-speed table-driven implementation
  2026. for CRC algorithms that is superior to the tea-leaf algorithm.
  2027. Although this paper describes the technique used by most modern CRC
  2028. implementations, I found the appendix of this paper (where all the
  2029. good stuff is) difficult to understand.
  2030.  
  2031. [Tanenbaum81] Tanenbaum, A.S., "Computer Networks", Prentice Hall,
  2032. 1981, ISBN: 0-13-164699-0. Comment: Section 3.5.3 on pages 128 to 132
  2033. provides a very clear description of CRC codes. However, it does not
  2034. describe table-driven implementation techniques.
  2035.  
  2036.  
  2037. C. References I Have Detected But Haven't Yet Sighted
  2038. -----------------------------------------------------
  2039. Boudreau, Steen, "Cyclic Redundancy Checking by Program," AFIPS
  2040. Proceedings, Vol. 39, 1971.
  2041.  
  2042. Davies, Barber, "Computer Networks and Their Protocols," J. Wiley &
  2043. Sons, 1979.
  2044.  
  2045. Higginson, Kirstein, "On the Computation of Cyclic Redundancy Checks
  2046. by Program," The Computer Journal (British), Vol. 16, No. 1, Feb 1973.
  2047.  
  2048. McNamara, J. E., "Technical Aspects of Data Communication," 2nd
  2049. Edition, Digital Press, Bedford, Massachusetts, 1982.
  2050.  
  2051. Marton and Frambs, "A Cyclic Redundancy Checking (CRC) Algorithm,"
  2052. Honeywell Computer Journal, Vol. 5, No. 3, 1971.
  2053.  
  2054. Nelson M., "File verification using CRC", Dr Dobbs Journal, May 1992,
  2055. pp.64-67.
  2056.  
  2057. Ramabadran T.V., Gaitonde S.S., "A tutorial on CRC computations", IEEE
  2058. Micro, Aug 1988.
  2059.  
  2060. Schwaderer W.D., "CRC Calculation", April 85 PC Tech Journal,
  2061. pp.118-133.
  2062.  
  2063. Ward R.K, Tabandeh M., "Error Correction and Detection, A Geometric
  2064. Approach" The Computer Journal, Vol. 27, No. 3, 1984, pp.246-253.
  2065.  
  2066. Wecker, S., "A Table-Lookup Algorithm for Software Computation of
  2067. Cyclic Redundancy Check (CRC)," Digital Equipment Corporation
  2068. memorandum, 1974.
  2069.  
  2070. ***** The END ******
  2071.